(function($) {
	$.fn.serializeJson = function() {
		var serializeObj = {};
		$.each(this.serializeArray(), function() {
			if (serializeObj[this.name]) {
				if ($.isArray(serializeObj[this.name])) {
					serializeObj[this.name].push(this.value);
				} else {
					serializeObj[this.name] = [ serializeObj[this.name], this.value ];
				}
			} else {
				serializeObj[this.name] = this.value;
			}
		});
		return serializeObj;
	};
})(jQuery);

var Ajax = {
	loadIndex : -1,
	post : function(url, params, fun, fail) {
		Ajax._load();
		$.ajax({
			type : "POST",
			url : url,
			data : params,
			dataType : "json",
			success : function(result) {
				if (result.success) {
					Ajax._success(this, result, fun);
				} else {
					Ajax._error(this, result, fail);
				}
			},
			error : function(message) {
				Ajax._error(this, message, fail);
			}
		});
	},
	json : function(url, params, fun, fail) {
		Ajax._load();
		$.ajax({
			type : "POST",
			url : url,
			contentType : "application/json; charset=utf-8",
			data : JSON.stringify(params),
			dataType : "json",
			success : function(result) {
				if (result.success) {
					Ajax._success(this, result, fun);
				} else {
					Ajax._error(this, result, fail);
				}
			},
			error : function(message) {
				Ajax._error(this, message, fail);
			}
		});
	},
	form : function(form, fun, fail) {
		Ajax._load();
		$.ajax({
			type : "POST",
			url : $(form).attr('action'),
			data : $(form).serialize(),
			dataType : "json",
			success : function(result) {
				if (result.success) {
					Ajax._success(this, result, fun);
				} else {
					Ajax._error(this, result, fail);
				}
			},
			error : function(message) {
				Ajax._error(this, message, fail);
			}
		});
		return false;
	},
	html : function(url, params, fun, fail) {
		Ajax._load();
		$.ajax({
			type : "POST",
			url : url,
			data : params,
			dataType : "html",
			success : function(result) {
				Ajax._success(this, result, fun);
			},
			error : function(message) {
				Ajax._error(this, message, fail);
			}
		});
	},
	_load : function() {
		Ajax.loadIndex = layer.msg('正在加载', {
			icon : 16,
			time : 0
		});
	},
	_success : function(_this, result, fun) {
		layer.close(Ajax.loadIndex);
		if (typeof (fun) == "function") {
			fun.call(_this, result);
		}
	},
	_error : function(_this, err, fun) {
		layer.close(Ajax.loadIndex);
		layer.msg(err.msg || err.statusText || "连接失败", {
			icon : 2,
			time : 1500
		});
		if (typeof (fun) == "function") {
			fun.call(_this, err);
		}
	}
}